package com.example.demo.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import javax.sound.midi.Soundbank;
import java.util.concurrent.TimeUnit;

/**
 * Description: TODO
 *
 * @author jihe.d
 * @date 2019/12/20 15:21
 */
public class Client {

    public static class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            //ctx.writeAndFlush(Unpooled.copiedBuffer("hello world".getBytes(CharsetUtil.UTF_8)));
        }
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {

            System.out.println("接收到服务器端信息：" + msg.toString(CharsetUtil.UTF_8));
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup(1);
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });

        Channel channel = bootstrap.connect("localhost", 8989).sync().channel();
        int i = 0;
        while (true) {
            i++;
            ChannelFuture future = channel.writeAndFlush(Unpooled.copiedBuffer(BytesUtil.int2Bytes(i)));
            future.sync();
//            System.out.println(channel.isOpen());
//            System.out.println(channel.isActive());
//            System.out.println(channel.isWritable());

        }
    }

}
